<template>
  <div>
    <h2>你好，我是模型管理助手，请问有什么可以帮你的吗？</h2>
    <el-scrollbar height="550px" width="50vw">
      <p v-for="(item, index) in messageList" :key="index">
        {{ item.role }} : <span v-html="item.content"></span>
      </p>
    </el-scrollbar>
    <el-space>
      <el-input
        v-model="inputQuestion"
        type="textarea"
        rows="4"
        style="width: 700px"
        placeholder=""
      />
      <!-- <button @click="sendStreamRequest">发送</button> -->
      <el-button @click="sendStreamRequest" :disabled="answering" type="primary"
        >发送</el-button
      ></el-space
    >
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// import { useRoute } from "vue-router";
// import marked from "marked";
import { marked } from "marked";
// const route = useRoute();

defineProps({
  msg: String,
});

const username = "alm";
const inputQuestion = ref("");
// const userId = ref("");
// const answer = ref("");
// const token = ref("");
const answering = ref(false);
const messageList = ref([]);
const sendStreamRequest = async () => {
  const url = new URL(window.location.href);
  const token = url.searchParams.get("token"); // "abc123"
  answering.value = true;
  let userMessage = { role: "你", content: inputQuestion.value };
  let message = inputQuestion.value;
  inputQuestion.value = "";
  messageList.value.push(userMessage);
  try {
    const res = await fetch("http://localhost:9000/ai/stream", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message,
        memoryId: username,
        token,
      }),
    });
    const reader = res.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let aiMessage = {
      role: "AI",
      content: "",
    };
    messageList.value.push(aiMessage);

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        answering.value = false;
        break;
      }
      const chunk = decoder.decode(value);
      aiMessage.content += chunk;
      messageList.value.pop();
      messageList.value.push({
        role: aiMessage.role,
        content: marked(aiMessage.content),
      });
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  // console.log("route", route);
  // messageList.value.push({
  //   role: "AI",
  //   content: "你好，我是模型管理助手，请问有什么可以帮你的吗？",
  // });
});
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
